import React, {PureComponent} from 'react';
import {connect} from 'dva';
import {Button, Card, Form, message} from 'antd';
import {PageHeaderWrapper} from '@ant-design/pro-layout';
import List from './components/List'
import MenuModal from './components/Modal'
import styles from './index.less';

@connect(state => ({
  menu: state.menu,
}))
@Form.create()
export default class index extends PureComponent {
  state = {
    modalVisible: false,
    selectedRows: [],
    items: {},
    modalType: 'add',
  };

  componentDidMount() {
    const {dispatch} = this.props;
    dispatch({
      type: 'menu/fetch',
    });
  }

  handleSelectRows = (rows) => {
    this.setState({
      selectedRows: rows,
    });
  }

  handleAddModal = () => {
    var selectedRows = this.state.selectedRows;
    if (selectedRows && selectedRows.length > 1) {
      message.warn("新增时最多只能勾选一条数据！");
      return;
    }

    if (selectedRows && selectedRows.length === 1) {
      this.setState({
        items: {
          parentId: selectedRows[0].id,
          parentName: selectedRows[0].name
        }
      })
    }

    this.setState({
      modalVisible: true,
      modalType: 'add'
    });
  }

  handleModalCancel = () => {
    this.setState({
      modalVisible: false,
      items: {}
    });
  }

  onEditItem = (item, flag) => {
    console.log(item);
    this.setState({
      modalVisible: !!flag,
      items: item,
      modalType: 'edit'
    });
  }

  handleSave = (values, form) => {
    this.props.dispatch({
      type: 'menu/' + this.state.modalType,
      payload: values,
      callback: (result) => {
        if (result.resultCode === "1") {
          this.setState({
            modalVisible: false,
            items: {}
          });
          form.resetFields();
          message.success(result.resultDesc);

        } else {
          message.error('操作失败！');
        }
      },
    });
  }


  render() {
    const {menu: {loading, data}} = this.props;
    const {selectedRows, modalVisible, modalType, items} = this.state;

    return (
      <PageHeaderWrapper title="菜单列表">
        <Card bordered={false}>
          <div className={styles.tableList}>
            <div className={styles.tableListOperator}>
              <Button style={{width:'100%'}} icon="plus" type="dashed" onClick={this.handleAddModal}>
                新建
              </Button>
            </div>
            <List
              selectedRows={selectedRows}
              loading={loading}
              data={data}
              onSelectRow={this.handleSelectRows}
              onEditItem={this.onEditItem}
            />
          </div>
        </Card>
        <MenuModal
          key={Date.now()}
          modalType={modalType}
          modalVisible={modalVisible}
          handleSave={this.handleSave}
          handleModalCancel={this.handleModalCancel}
          items={items}
        />
      </PageHeaderWrapper>
    );
  }
}
